var tbl = document.getElementById("table");

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
  switch (request.type) {
    case "inject":
      sendResponse(localStorage.inject == "true");
      break;
    case "get":
      sendResponse(tbl.innerHTML);
      break;
    case "disarm":
      Investor.disarm(request.secid, request.trigger).save();
      break;
    default:
      sendResponse({}); // snub
      break;
  }
});

Metrics.add("secid",        "text",   function() { return this.secid; });
Metrics.add("title",        "text",   function() { return this.title; });
Metrics.add("value",        "value",  function() { return this.value; });
Metrics.add("change",       "change", function() { return this.change; });
Metrics.add("pctChange",    "pct",    function() { return this.change / (this.value - this.change) * 100; });
Metrics.add("portValue",    "value",  function() { return this.count * this.value; },
  function() { return this.count * this.value; });
Metrics.add("dailyGain",    "change", function() { return this.count * this.change; },
  function() { return this.count * this.change; });
Metrics.add("dailyPctGain", "pct",  function() { return (this.count == 0 ? 0 : (this.change / (this.value - this.change) * 100)); },
  function() { return this.count * this.change * 100; },
  function() { return this.count * (this.value - this.change); });
Metrics.add("totalGain",    "change", function() { return this.count * (this.value - this.pricePaid); },
  function() { return this.count * (this.value - this.pricePaid); });
Metrics.add("totalPctGain", "pct",    function() { return (this.pricePaid == 0 ? 0 : this.value / this.pricePaid - 1) * 100; },
  function() { return this.count * (this.value - this.pricePaid) * 100; },
  function() { return this.count * this.pricePaid; });
Metrics.add("pricePaid",    "value",  function() { return this.pricePaid; });
Metrics.add("initInvest",   "value",  function() { return this.count * this.pricePaid; },
  function() { return this.count * this.pricePaid; });

Sources.add(
  "bloomberg", "http://www.bloomberg.com/apps/quote?ticker=",
  "http://www.bloomberg.com/flashsrv/chart.swf", "ticker={secid}",
  637, 570, "transparent",
  /<title>.*?\:\s(.*?)(?:(?:\s|\/){0,2}(?:Inc|The|Group|Corp|\&amp\; Co)*?)*?\sSummary/,
  /<span class="amount">([0-9,.]*?)</,
  /<td class="name">Change<\/td>\n<td class="value.*?">(.*?)\s\(/
);
Sources.add(
  "google", "http://www.google.com/finance?q=",
  "http://www.google.com/finance/chart9.swf", "q={secid}&lcId=1269509101766&single_viewpoints=name%3AMainViewPoint%2Cheight%3A202%2CtopMargin%3A0&single_layers=vp%3AMainViewPoint%2Cname%3ADateLinesLayer%2Carity%3AUnique%2CtickPosition%3A0%2Ctype%3Asimple%2ChasText%3Atrue%3A%3Avp%3AMainViewPoint%2Cname%3APriceLinesLayer%2Carity%3AUnique%2Ctype%3Asimple%3A%3Avp%3AMainViewPoint%2Cname%3ALineChartLayer%2Carity%3AUnique%2Ctype%3Asimple%3A%3Avp%3AMainViewPoint%2Cname%3AAHLineChartLayer%2Carity%3AUnique%2Ctype%3Asimple%3A%3Avp%3AMainViewPoint%2Cname%3ALastDayLineLayer%2Carity%3AUnique%2Ctype%3Asimple%3A%3Avp%3AMainViewPoint%2Cname%3ABottomBarLayer%2Carity%3AUnique%2Ctype%3Asimple&compare_viewpoints=name%3AMainViewPoint%2Cheight%3A247%2CtopMargin%3A15&compare_layers=vp%3AMainViewPoint%2Cname%3APercentLinesLayer%2Carity%3AUnique%2Ctype%3Asimple%3A%3Avp%3AMainViewPoint%2Cname%3ADateLinesLayer%2Carity%3AUnique%2Ctype%3Asimple%2CtickPosition%3A0%3A%3Avp%3AMainViewPoint%2Cname%3ABottomBarLayer%2Carity%3AUnique%2Ctype%3Asimple%3A%3Avp%3AMainViewPoint%2Cname%3APercentLineChartLayer%2Carity%3AMultiple%2Ctype%3Asimple&u=http://www.google.com/finance/getprices&fieldSeparator=%2C&objectSeparator=%3A%3A&sparklineType=dynamic&disableExternalInterface=true",
  440, 300, "transparent",
  /<title>(.*?)(?:\sInc\.)*?\:/,
  /<span id="ref_[0-9]*?_l">([0-9,.]*?)</,
  /<span class="chg?r?" id="ref_[0-9]*?_c">\+?(\-?[0-9,.]*?)</
);
Sources.add(
  "yahoo", "http://finance.yahoo.com/q?s=",
  "http://us.js2.yimg.com/us.js.yimg.com/lib/fi/201008171841/us/swf/yfcv3/flashchart.swf",
  "lcId=1284608380199&amp;localeUri=http%3A//us.js2.yimg.com/us.js.yimg.com/lib/fi/201008171841/us/locale/yfcv3/dictionary.xml&amp;chartHost=chartapi.finance.yahoo.com&amp;keyeventsHost=finance.yahoo.com&amp;sigdevsHost=ads.finance.yahoo.com&amp;buildType=prod&amp;state=symbol%3D{secid}%3Brange%3D1d%3Bindicator%3Dvolume%3Bcharttype%3Dline%3Bcrosshair%3Don%3Bohlcvalues%3D0%3Blogscale%3Don&amp;source=undefined",
  512, 490, "opaque",
  /Summary\sfor\s(.*?)(?:(?:\s|,|\/){0,2}(?:Inc\.|The|Group|Corp|\&amp\; Co)*?)*?\-/,
  /<span id="yfs_l10_.*?">(.*?)</,
  /<span id="yfs_c10_.*?"[^>]+>.*?\n.*?\n.*?>(.*?)</
);
Sources.add(
  "quote", "http://www.quote.com/us/stocks/quote.action?s=",
  "http://www.quote.com/beta/index.swf",
  "ServerURL=http%3A//www.quote.com/feed/jmaf%3F&Symbols=%24INDU&Aggregation=5D&ShowToolbar=true&ShowHeader=true&HeaderFg=000000&HeaderBg=FFFFFF&XAxisFg=00025E&YAxisFg=00025E&XAxisBg=&YAxisBg=&ShowSymbolField=true&ShowToolbarGoBtn=true&ShowToolbarAddBtn=true&ShowToolbarChartTypeBtn=true&ChartType=line&ShowToolbarChartCursorBtn=true&ShowToolbarAggregationBtn=true&ShowToolbarChartSettingsBtn=true&ShowToolbarStudiesBtn=true&ShowValueMarkers=true&SymChangeCallback=switchMenu",
  900, 450, "transparent",
  /<li class="title">(.*?)\s\(.*?\)</,
  /Last\:\s<span class="majors">(.*?)</,
  /Chg\:\s<span class=".*?">(.*?)</
);

// if (Settings.sync()) {
//   sync(function() { portfolios.load(); });
// } else {
//  Investor.load();
// }

function updateTable() {
  Investor.current().updateTable(tbl);
}

Investor.drawTable(tbl);
setInterval(updateTable, 15000);

/*
$.ajax({
  url: "http://www.google.com/finance/portfolio?action=viewt&pid=1&output=csv",
  success: function(data) {
    var blah = {};
    var temp = data.split("\n");
    var isTopRow = true;
    $.each(temp, function(index, row) {
      if (!isTopRow) {
        var items = row.split(",");
        if (items[0] in blah) {
          blah[items[0]] += parseFloat(items[4]);
        } else {
          blah[items[0]] = parseFloat(items[4]);
        }
      } else {
        isTopRow = false;
      }
    });
    // alert(JSON.stringify(blah));
  }
});
*/